int multiplex_sync(unsigned char *c, const int c_size, const unsigned char *a, const int a_len, const unsigned char *b, const int b_len) {
    if (c_size < 8 + a_len + b_len) return -1;
    for (int i = 0; i < 4; i++) c[i] = (a_len >> (8 * i)) & 0xFF;
    for (int i = 0; i < 4; i++) c[4 + i] = (b_len >> (8 * i)) & 0xFF;
    int j = 8;
    int min_len = a_len < b_len ? a_len : b_len;
    for (int i = 0; i < min_len; i++) {
        c[j++] = a[i];
        c[j++] = b[i];
    }
    if (a_len > b_len) {
        for (int i = min_len; i < a_len; i++) c[j++] = a[i];
    } else if (b_len > a_len) {
        for (int i = min_len; i < b_len; i++) c[j++] = b[i];
    }
    return 0;
}

int demultiplex_sync(unsigned char *a, const int a_size, unsigned char *b, const int b_size, const unsigned char *c, const int c_len) {
    int a_len = 0, b_len = 0;
    for (int i = 0; i < 4; i++) a_len |= (c[i] << (8 * i));
    for (int i = 0; i < 4; i++) b_len |= (c[4 + i] << (8 * i));
    int actual_a_len = a_len < a_size ? a_len : a_size;
    int actual_b_len = b_len < b_size ? b_len : b_size;
    int K = actual_a_len < actual_b_len ? actual_a_len : actual_b_len;
    int index = 8;
    for (int i = 0; i < K; i++) {
        a[i] = c[index++];
        b[i] = c[index++];
    }
    if (a_len > b_len && actual_a_len > K) {
        for (int i = 0; i < actual_a_len - K; i++) a[K + i] = c[index++];
    }
    if (b_len > a_len && actual_b_len > K) {
        for (int i = 0; i < actual_b_len - K; i++) b[K + i] = c[index++];
    }
    return 0;
}